//
//  GPLocationManager.m
//  Keping
//
//  Created by 23 on 2017/12/10.
//  Copyright © 2017年 柯平. All rights reserved.
//

#import "GPLocationManager.h"

@interface GPLocationManager () <CLLocationManagerDelegate>

/**当前位置*/
@property(nonatomic,strong) CLLocation *currentLocation;
/**callback*/
@property(nonatomic,copy) GPLocationManagerCallback callback;

@end

@implementation GPLocationManager

static id _instance;

+ (instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[self alloc] init];
    });
    return _instance;
}

- (instancetype)init
{
    if (self = [super init]) {
        
        self.delegate = self;
        //控制定位精度,越高耗电量越
        self.desiredAccuracy = kCLLocationAccuracyKilometer;
        // 总是授权
        [self requestAlwaysAuthorization];
        self.distanceFilter = 10.0f;
        [self requestAlwaysAuthorization];
        [self startUpdatingLocation];
    }
    return self;
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}
//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *newLocation = locations[0];
    
    self.currentLocation = newLocation;
    // 获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error){
        if (array.count > 0){
           
            CLPlacemark *placemark = [array objectAtIndex:0];
            
            if (self.callback) {
                self.callback(YES, newLocation, placemark);
            }
            
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
            if (self.callback) {
                self.callback(YES, newLocation, nil);
            }
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
            if (self.callback) {
                self.callback(YES, newLocation, nil);
            }
        }
    }];
    
    
    //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
    [manager stopUpdatingLocation];
    
}


- (void)requestCurrentLocationOnce:(void(^)(BOOL success, CLLocation *location, CLPlacemark *placemark))completion
{
    self.callback = completion;
    
    [self startUpdatingLocation];
    
}



@end
